package com.code.chatroom.client

import io.netty.bootstrap.Bootstrap
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel

/**
 * 聊天室客户端
 */
class ChatRoomClient(private val host : String, private  val port : Int = 7651) {

    /**
     * 启动客户端
     */
    fun start(){
        val group = NioEventLoopGroup()
        val bootstrap = Bootstrap()
        bootstrap.group(group)
            .channel(NioSocketChannel::class.java)
            .handler(InitChannelHandler())

        try {
            val future = bootstrap.connect(host, port).sync()
            // 获取用户输入
            while (true){
                val str = readLine()
                future.channel().writeAndFlush(str)
            }
        }catch (e : Exception){
            println("无法连接到服务器，请检查网络设置...")
        }finally {
            group.shutdownGracefully()
        }


    }
}